package com.siyu.tickets.manager.impl;

import java.math.BigDecimal;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.siyu.common.exception.MessageException;
import com.siyu.tickets.dao.SupplierDao;
import com.siyu.tickets.dao.TicketDao;
import com.siyu.tickets.dao.TicketVerifyDao;
import com.siyu.tickets.entity.Supplier;
import com.siyu.tickets.entity.Ticket;
import com.siyu.tickets.entity.TicketVerify;
import com.siyu.tickets.manager.TicketMng;

@Service
@Transactional
public class TicketMngImpl implements TicketMng {

	public Ticket validate(Integer supplierId, String code, Integer count) {
		Ticket ticket = dao.findByCode(code);
		if (ticket == null) {
			throw new MessageException("无效的电子码");
		}
		Integer maxCount = ticket.getOrder().getQuantity();
		if (maxCount - ticket.getVerifyCount() < count) {
			throw new MessageException("输入电子票数目大于未验证电子票数目");
		}
		// 开始验证
		Date now = new Date();
		ticket.setVerifyCount(ticket.getVerifyCount() + count);
		ticket.setConsumeTime(now);
		// 验证记录日志
		Supplier supplier = suplierDao.findById(supplierId);
		BigDecimal money = ticket.getProduct().getPartnerPrice().multiply(new BigDecimal(count));// 验证金额等于商品供应商单价金额*验证张数
		TicketVerify record = new TicketVerify();
		record.setCreateTime(now);
		record.setProduct(ticket.getProduct());
		record.setSupplier(supplier);
		record.setTicket(ticket);
		record.setVerifyCount(count);
		record.setVerifyMoney(money);
		ticketVerifyDao.save(record);

		return ticket;
	}

	public Ticket findByCode(String code) {
		return dao.findByCode(code);
	}

	@Autowired
	private TicketDao dao;

	@Autowired
	private TicketVerifyDao ticketVerifyDao;

	@Autowired
	private SupplierDao suplierDao;

}
